$(function() {
    let pic2;
    // alert('ok')
    var form = layui.form;
    let pic = null;
    var laydate = layui.laydate;
    // layui.laydate.index = Date.now();
    var q = {
        start_time: '',
        end_time: '',
        title: '',
        cateid: '',
        page: '1',
        limit: '10',
    };

    // 时间处理补零
    template.defaults.imports.tplTime = function(data) {
        var dt = new Date(data);

        var y = dt.getFullYear();
        var m = padZero(dt.getMonth() + 1);
        var d = padZero(dt.getDate());

        var hh = padZero(dt.getHours());
        var mm = padZero(dt.getMinutes());
        var ss = padZero(dt.getSeconds());

        return y + '-' + m + '-' + d + ' ' + hh + ':' + mm + ':' + ss;
    };

    function padZero(n) {
        return n > 9 ? n : '0' + n;
    }

    // 时间选择器
    layui.use('laydate', function() {
        var laydate = layui.laydate;

        //执行一个laydate实例
        laydate.render({
            elem: '#test1', //指定元素

            range: '至',
        });
    });

    $('body').on('change', '#files', function(e) {
        let fd = new FormData();
        console.log(fd);
        fd.append('file', $('#files')[0].files[0]);
        $.ajax({
            url: 'http://124.223.14.236:8060/common/upload?type=images',
            method: 'POST',
            data: fd,
            headers: {
                token: localStorage.getItem('token'),
            }, // 注意：formData格式的请求要加上下面两项配置
            contentType: false,
            processData: false,
            success: function(res) {
                // console.log(res);
                pic = res.data.savePath;
                pic2 = res.data.savePath;
                // console.log(pic2);
            },
        });
    });
        // 添加弹出框  图片
        $('body').on('change', '#files2', function(e) {
            let fd = new FormData();
            fd.append('file', $('#files2')[0].files[0]);
            $.ajax({
                url: 'http://124.223.14.236:8060/common/upload?type=images',
                method: 'POST',
                data: fd,
                headers: {
                    token: localStorage.getItem('x-token'),
                }, // 注意：formData格式的请求要加上下面两项配置
                contentType: false,
                processData: false,
                success: function(res) {
                    // console.log(res);
                    pic2 = res.data.savePath;
                    // console.log(pic2);
                },
            });
        });

    $('#i_reload').click(function() {
        // console.log(1);
        getArtList();
    });

    // 渲染表格整体数据

    // 函数封装
    function getArtList() {
        axios({
            method: 'GET',
            url: 'http://124.223.14.236:8060/admin/ydd_article/list',
            headers: {
                'x-token': localStorage.getItem('token'),
            },
        }).then(function(res) {
            // console.log(res.data);
            const htmlStr = template('titleTpl', res.data.data);
            // console.log(htmlStr);
            form.render();
            $('tbody').html(htmlStr);
            form.render();
            getPaging(res.data.data.count);
        });
        form.render('checkbox');
    }
    getArtList();



    // 搜索按钮
    $('#selectForm').on('submit', function(e) {
        e.preventDefault();
        q.title = $('#title').val();
        q.cateid = $('#select option:selected').val(); //获取属性value的值
        time = $('#test1').val();
        const start_time = time.substring(0, 10);
        const end_time = time.substring(12);
        axios({
            method: 'GET',
            url: 'http://124.223.14.236:8060/admin/ydd_article/list',
            params: { title: $('#title').val(), cateid: $('#select option:selected').val(), start_time: start_time, end_time: end_time },
            headers: {
                'x-token': localStorage.getItem('token'),
            },
        }).then(function(res) {
            // console.log(res.data);
            const htmlStr = template('titleTpl', res.data.data);
            form.render();
            // console.log(htmlStr);
            $('tbody').html(htmlStr);
            getPaging(res.data.data.count);
        });
    });

    // 重置按钮
    $('#resetBtn').on('click', function() {
        q.title = '';
        q.cateid = '';
        q.create_date = '';
        getArtList();
        $('.check').prop('checked', true);
    });

    // 分页区域
    function getPaging(count) {
        layui.use('laypage', function() {
            var laypage = layui.laypage;
            //执行一个laypage实例
            laypage.render({
                elem: 'paging', //注意，这里的 test1 是 ID，不用加 # 号
                count, //数据总数，从服务端得到
                limit: q.limit,
                curr: q.page,
                limits: [10, 8, 6, 4, 2],
                layout: ['count', 'limit', 'prev', 'page', 'next', 'skip'],
                jump: function(obj, first) {
                    q.page = obj.curr;
                    q.limit = obj.limit;
                    if (!first) {
                        axios({
                            method: 'GET',
                            url: 'http://124.223.14.236:8060/admin/ydd_article/list',
                            params: { page: obj.curr, limit: obj.limit },

                            headers: {
                                'x-token': localStorage.getItem('token'),
                            },
                        }).then(function(res) {
                            // console.log(res.data);
                            const htmlStr = template('titleTpl', res.data.data);
                            // console.log(res.data.data.create_date);
                            // console.log(htmlStr);
                            $('tbody').html(htmlStr);
                            form.render();
                            getPaging(res.data.data.count);
                        });
                    }
                },
            });
        });
    }

    // 删除功能
    $('tbody').on('click', '#btnDel', function() {
        var id = $(this).attr('data-id');
        layer.confirm(
            '确认删除吗?', {
                icon: 3,
                title: '提示',
            },
            function(index) {
                axios({
                    method: 'GET',
                    url: 'http://124.223.14.236:8060/admin/ydd_article/del',
                    params: {
                        id: id,
                    },
                    headers: {
                        'x-token': localStorage.getItem('token'),
                    },
                }).then(function(res) {
                    // console.log(res);
                    if (res.status !== 200) {
                        return layer.msg('删除失败！');
                    }
                    layer.msg('删除成功！');
                    getArtList();
                });
                // layer.close(index);
            },
        );
    });

    // 添加数据
    var addBtnClose = null;
    $('#btnAdd').on('click', function() {
        form.render();
        select();
        addBtnClose = layer.open({
            title: '新增文章',
            type: 1,
            area: ['850px', '550px'],
            content: $('#addListTpl').html(), 
        });
     
        // 时间选项
        laydate.render({
            elem: '#time_text', //指定元素
            type: 'datetime',
            trigger: 'click', //加入click事件
        });
        form.render();
    });

    // 下拉框数据
    function select() {
        axios({
            method: 'get',
            url: 'http://124.223.14.236:8060/admin/ydd_cate/all',
            headers: {
                'x-token': localStorage.getItem('token'),
            },
        }).then(function(res) {
            // console.log(res);
            let htmlArr = res.data.data.map(item => {
                return `<option value="${item.id}">${item.catename}</option>`;
            });
            // console.log(htmlArr);
            $('#catename').html(htmlArr.join(''));
            $('#cateid').html(htmlArr.join(''));
            form.render();
        });
    }
    // 新增按钮
    $('body').on('submit', '#addFormList', function(e) {
        // console.log($('#time_text').val());
        e.preventDefault();
        let catename = $('#catename').val();
        let ishot = $('#tuijian1').prop('checked') ? 1 : 0;
        let istop = $('#tuijian2').prop('checked') ? 1 : 0;
        // console.log(istop);
        // console.log($(this).serialize() + '&pic=' + pic + '&cateid=' + catename + '&create_date=' + Date.parse($('#time_text').val()) + '&ishot=' + ishot + '&istop=' + istop);
        axios({
            method: 'POST',
            url: 'http://124.223.14.236:8060/admin/ydd_article/add',
            data: $(this).serialize() + '&pic=' + pic + '&cateid=' + catename + '&create_date=' + Date.parse($('#time_text').val()) + '&ishot=' + ishot + '&istop=' + istop,
            headers: {
                'x-token': localStorage.getItem('token'),
            },
        }).then(function(res) {
            // console.log(res);
            if (res.data.errno !== 0) return layer.msg('添加失败');
            layer.msg('添加成功');
            getArtList();
            form.render();
            layer.close(addBtnClose);
        });
    });

    // 修改数据
    let go_id = null;
    $('tbody').on('click', '#editBtn', function() {
        go_id = $(this).attr('data-id');
        addBtnClose = layer.open({
            title: '修改文章',
            type: 1,
            area: ['850px', '550px'],
            content: $('#addTplList').html(), 
        });
        let i = $(this).attr('data-id');
        axios({
            method: 'post',
            url: 'http://124.223.14.236:8060/admin/ydd_cate/all',
            data: { id: i },
            headers: {
                'x-token': localStorage.getItem('token'),
            },
        }).then(function(res) {
            let htmlArr = res.data.data.map(item => {
                return `<option value="${item.id}">${item.catename}</option>`;
            });
            $('#catename').html(htmlArr.join(''));
      
            // 时间选择器
            laydate.render({
                elem: '#time_text1', //指定元素
                type: 'datetime',
                trigger: 'click', //加入click事件
            });
            $('#cate_id').html(htmlArr.join(''));
            form.render();
        });

    //    修改时获取表单数据
        var id = $(this).attr('data-id');
        axios({
            method: 'GET',
            url: 'http://124.223.14.236:8060/admin/ydd_article/rowInfo',
            params: {
                id: id,
            },
            headers: {
                'x-token': localStorage.getItem('token'),
            },
        }).then(function(res) {
            // console.log(res);
            let v = res.data.data;
            $('#addFormList1 input[name=title]').val(v.title);
            $('#addFormList1 input[name=author]').val(v.author);
            $('#addFormList1 input[name=click]').val(v.click);
            $('#addFormList1 input[name=cateid]').val(v.cateid);
            $('#addFormList1 input[name=tags]').val(v.tags);
            // $('#addFormList1 input[name=cateid]').val(v.city);
        //     if (v.ishot === 0) {
        //         $('#sw1').html(`<label class="layui-form-label">是否推荐</label>
        // <input type="checkbox" name="yyy" lay-skin="switch" lay-text="ON|OFF" />`);
        //         form.render();
        //     } else if (v.ishot === 1) {
        //         form.render();
        //         $('#sw1').html(`<label class="layui-form-label">是否推荐</label>
        // <input type="checkbox" name="yyy" lay-skin="switch" lay-text="ON|OFF" checked/>`);
        //         form.render();
        //     }

        //     if (v.istop == 0) {
        //         $('#sw2').html(`<label class="layui-form-label">是否置顶</label>
        // <input type="checkbox" name="yyy" lay-skin="switch" lay-text="ON|OFF" class="switch2"  />`);
        //         form.render();
        //     } else {
        //         $('#sw2').html(`<label class="layui-form-label">是否置顶</label>
        // <input type="checkbox" name="yyy" lay-skin="switch" lay-text="ON|OFF" class="switch2" checked />`);
        //         form.render();
        //     }
           
            $('#addFormList1 input[name=lovenum]').val(v.lovenum);
            $('#addFormList1 textarea[name=keywords]').val(v.keywords);
            $('#addFormList1 textarea[name=description]').val(v.description);
            $('#addFormList1 textarea[name=content]').val(v.content);

          
        });
    });
    
    // 上传修改后表格数据提交到服务器
    $('body').on('submit', '#addFormList1', function(e) {
        e.preventDefault();
        let ishot = $('#sw1 input').prop('checked') ? 1 : 0;
        let istop = $('#sw2 input').prop('checked') ? 1 : 0;
        // let data= form.val('addFormList')
        let data = {
            // cateid: '38',
            title: $('#addListForms [name=title]').val(),
            click: $('#addListForms [name=click]').val(),
            cateid: $('#addListForms [name=cateid]').val(),
      
            author: $('#addListForms [name=author]').val(),
            create_date: Date.parse($('#time_text1').val()),
            lovenum: $('#addListForms [name=lovenum]').val(),
            tags: $('#addListForms [name=tags]').val(),
            keywords: $('#addListForms [name=keywords]').val(),
            content: $('#addListForms [name=content]').val(),
            pic: pic2,
            ishot: ishot,
            istop: istop,
            status: '2',
            id: parseInt(go_id),
        };
        // console.log(data);
        axios({
            method: 'POST',
            url: 'http://124.223.14.236:8060/admin/ydd_article/update',
            data: data,
            headers: {
                'x-token': localStorage.getItem('token'),
            },
        }).then(function(res) {
            layer.msg('修改成功');
            getArtList();
            layer.close(addBtnClose);
        });
    });


    
    $('body').on('click', '#backBtn', function() {
        layer.close(addBtnClose);
    });

    // 导出
    $('#vanishTop').on('click', function() {
        $('#selectForm').hide();
        $(this).hide();
        $('#vanishDown').show();
    });
    $('#vanishDown').on('click', function() {
        $('#selectForm').show();
        $(this).hide();
        $('#vanishTop').show();
    });

    $('body').on('click', '#addFile', function() {
        $('#files2')[0].click();
    });
    $('body').on('click', '#addFile2', function() {
        $('#files')[0].click();
    });

    $('#table_xl').click(function() {
        $('.adv-box').toggle();
    });

    $('.check').prop('checked', true);
    let btns = document.querySelectorAll('.check');
    for (let i = 0; i < btns.length; i++) {
        btns[i].setAttribute('index', i);
        btns[i].onclick = function() {
            index = this.getAttribute('data-checked');
            // console.log(index);
            if (index == 0) {
                $('.xl_one1').toggleClass('all');
            } else if (index == 1) {
                $('.xl_one2').toggleClass('all');
            } else if (index == 2) {
                $('.xl_one3').toggleClass('all');
            } else if (index == 3) {
                $('.xl_one4').toggleClass('all');
            } else if (index == 4) {
                $('.xl_one5').toggleClass('all');
            } else if (index == 5) {
                $('.xl_one6').toggleClass('all');
            } else if (index == 6) {
                $('.xl_one7').toggleClass('all');
            } else if (index == 7) {
                $('.xl_one8').toggleClass('all');
            } else if (index == 8) {
                $('.xl_one9').toggleClass('all');
            }
        };
    }

    $('#export').click(function(e) {
        var table = $('.layui-table');
        var preserveColors = table.hasClass('table2excel_with_colors') ? true : false;
        $(table).table2excel({
            exclude: '.noExl',
            name: 'Excel Document Name',
            filename: 'myFileName' + new Date().toISOString().replace(/[\-\:\.]/g, '') + '.xls',
            fileext: '.xls',
            exclude_img: true,
            exclude_links: true,
            exclude_inputs: true,
            preserveColors: preserveColors,
        });
    });
});